#include <spi.hpp>

#define SPI_HOST	 SPI2_HOST

#define PIN_NUM_MISO 13
#define PIN_NUM_MOSI 12
#define PIN_NUM_CLK	 14
#define PIN_NUM_CS	 21

SPI::SPI()
{
#if defined(CONFIG_TAR4ESP32)
	memset(&spi, 0, sizeof(spi_device_handle_t));
	memset(&buscfg, 0, sizeof(spi_bus_config_t));
	memset(&devcfg, 0, sizeof(spi_device_interface_config_t));

	buscfg.miso_io_num	   = PIN_NUM_MISO;
	buscfg.mosi_io_num	   = PIN_NUM_MOSI;
	buscfg.sclk_io_num	   = PIN_NUM_CLK;
	buscfg.quadwp_io_num   = -1;
	buscfg.quadhd_io_num   = -1;
	buscfg.max_transfer_sz = 0x400;

	devcfg.command_bits	  = 0;
	devcfg.address_bits	  = 8;
	devcfg.clock_speed_hz = 26 * 1000 * 1000;
	devcfg.mode			  = 0;
	devcfg.spics_io_num	  = PIN_NUM_CS;
	devcfg.queue_size	  = 1;
	devcfg.pre_cb		  = NULL;

	spi_bus_initialize(SPI_HOST, &buscfg, SPI_DMA_CH_AUTO);
	spi_bus_add_device(SPI_HOST, &devcfg, &spi);
#endif
}
SPI::~SPI()
{
}

int SPI::Transfer(uint8_t addr, uint8_t* send, uint8_t* recv, int len)
{
	if (len <= 0)
	{
		return 0;
	}

#if defined(CONFIG_TAR4ESP32)
	spi_device_acquire_bus(spi, portMAX_DELAY);
	spi_transaction_t t;
	memset(&t, 0, sizeof(spi_transaction_t));
	t.addr		= addr;
	t.length	= 8 * len;
	t.rxlength	= 8 * len;
	t.tx_buffer = send;
	t.rx_buffer = recv;
	spi_device_polling_transmit(spi, &t);
	spi_device_release_bus(spi);
#endif

	return len;
}

int SPI::Write(uint8_t addr, uint8_t* data, uint16_t len)
{
	if (len <= 0)
	{
		return 0;
	}

#if defined(CONFIG_TAR4ESP32)
	spi_device_acquire_bus(spi, portMAX_DELAY);
	spi_transaction_t t;
	memset(&t, 0, sizeof(spi_transaction_t));
	t.flags		= 0;
	t.cmd		= 0;
	t.addr		= addr;
	t.length	= 8 * len;
	t.rxlength	= 0;
	t.user		= NULL;
	t.tx_buffer = data;
	t.rx_buffer = NULL;
	spi_device_polling_transmit(spi, &t);
	spi_device_release_bus(spi);
#endif

	return len;
}

int SPI::Read(uint8_t addr, uint8_t* data, uint16_t len)
{
	if (len <= 0)
	{
		return 0;
	}

#if defined(CONFIG_TAR4ESP32)
	spi_device_acquire_bus(spi, portMAX_DELAY);
	spi_transaction_t t;
	memset(&t, 0, sizeof(spi_transaction_t));
	t.flags		= 0;
	t.cmd		= 0;
	t.addr		= addr;
	t.length	= 8 * len;
	t.rxlength	= 8 * len;
	t.user		= NULL;
	t.tx_buffer = NULL;
	t.rx_buffer = data;
	spi_device_polling_transmit(spi, &t);
	spi_device_release_bus(spi);
#endif

	return len;
}
